package Class.Dialog;

import Class.Handler.*;
import Class.Dialog.*;
import Class.TextWindow.*;
import Class.Main.*;

import javax.swing.*;
import javax.swing.text.BadLocationException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

public class TurnToDialog extends JDialog implements ActionListener {

    private TextWindow textWindow;
    private JTextField lineField = new JTextField();
    private JButton virtuallineFieldButton = new JButton();
    private JButton turnToButton = new JButton("跳转(F)");


    public TurnToDialog(TextWindow textWindow){
        super(textWindow,"转到",true);
        this.textWindow=textWindow;

        //设置助记符
        turnToButton.setMnemonic(KeyEvent.VK_F);
        virtuallineFieldButton.setMnemonic(KeyEvent.VK_N);



        //建立框体，使用绝对布局，需指定坐标
        JPanel jPanel = new JPanel(null);
        JLabel findLabel = new JLabel("转到行(N):");

        //添加组件
        jPanel.add(virtuallineFieldButton);
        jPanel.add(findLabel);
        jPanel.add(lineField);
        jPanel.add(turnToButton);


        //对组件布局
        findLabel.setBounds(30,20,80,30);

        lineField.setBounds(100,20,280,30);

        turnToButton.addActionListener(this);
        turnToButton.setBounds(395,15,115,35);

        virtuallineFieldButton.addActionListener(this);

        this.getContentPane().add(jPanel);
        setSize(550,180);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);
        setVisible(true);

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == virtuallineFieldButton){
            lineField.requestFocusInWindow();
        } else if (e.getSource() == turnToButton) {
            String lineNumStr = lineField.getText();
            int lineNum;
            try {
                lineNum = Integer.parseInt(lineNumStr);
            }catch (Exception ex){
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this,"请输入数字");
                return;
            }
            int lineCount = textWindow.getTextArea().getLineCount();
            if( lineNum > lineCount){
                JOptionPane.showMessageDialog(this,"请输入不大于"+lineCount+"的行号");
                return;
            }
            try{
                textWindow.getTextArea().setCaretPosition(textWindow.getTextArea().getLineStartOffset(lineNum-1));
            }catch (BadLocationException ex){
                ex.printStackTrace();
            }
            this.dispose();
        }
    }
}
